package com.wxl.micro.service.order.listener;


import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.CircuitBreaker;
import com.alibaba.csp.sentinel.slots.block.degrade.circuitbreaker.EventObserverRegistry;
import com.alibaba.csp.sentinel.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * 熔断器状态变更监听
 */
@Component
public class DegradeAndFlowBlockEventListener {

    @PostConstruct
    public void degradeEventListener(){

        // 熔断器事件监听
        EventObserverRegistry.getInstance().addStateChangeObserver("logging",
                (prevState, newState, rule, snapshotValue) -> {
                    if (newState == CircuitBreaker.State.OPEN) {
                        // 变换至 OPEN state 时会携带触发时的值
                        System.err.println(String.format("打开熔断 %s -> OPEN at %d, snapshotValue=%.2f", prevState.name(),
                                TimeUtil.currentTimeMillis(), snapshotValue));
                    }else if (newState == CircuitBreaker.State.CLOSED) {
                        System.out.println("正常状态  不熔断  closed");
                    }else if (newState == CircuitBreaker.State.HALF_OPEN) {
                        System.err.println(String.format("熔断半开状态   %s -> %s at %d", prevState.name(), newState.name(),
                                TimeUtil.currentTimeMillis()));
                    }
                    System.out.println("熔断事件：" + JSON.toJSONString(rule));
                });
        // open   close   half-open   open
    }

}
